<template>
  <!-- :disabled="showCouponList || oilGunOrUserShow"  ：  在选择员工油枪以及选择优惠券时禁用下拉刷新事件 -->
  <!-- <van-pull-refresh v-model="isLoading" :disabled="showCouponList || oilGunOrUserShow || isShowOilEnginDialog"> -->
  <van-pull-refresh v-model="isLoading" :disabled="true">
    <div class="remitDiv" v-if="isShowPage">
      <div class="top_bg"></div>
      <div class="fuel_remit_wraper" :class="[showKeyboard || showRemitPage ? 'active' : '']">
        <div class="fuel_remit_nav" @click="goFuelPage()">
          <div class="name">{{ stationName }}</div>
          <div class="icon_right"></div>
        </div>
        <div class="remit_container">
          <div class="oilGun_container">
            <div class="fuel_remit_top" :class="[showRemitPage ? 'active' : '']" v-for="(item,index) in oilList" :key="index">
              <van-swipe-cell :disabled="oilList.length==1">
                  <!-- 金额 -->
                <div class="amount_of_money" >
                    <div class="amount_of_money_title">金额</div>
                    <van-field :readonly="appType == 3 ? true : false" v-model="item.priceValue"  @click="onFocusField(index)" :ref="'fieldRef'+`${index}`" @focus="onFocusField(index)" label="¥" class="field_price" :class="[!item.priceValue ? 'placeStyle' : '']" placeholder="加油金额(0.01-50000)">
                      <template #button>
                        <div v-show="showKeyboard && !!item.priceValue" class="icon_close" @click="deletePrice(index)"></div>
                        <div class="discountAmt" v-show="CouponDataList[index]&&CouponDataList[index].discountAmt > 0 && showRemitPage">立减￥{{CouponDataList[index]&&CouponDataList[index].discountAmt }}</div>
                      </template>
                    </van-field>
                    <!-- 推荐价格 -->
                    <div class="divider_line input" :class="[showKeyboard ? 'active' : '']" v-if="appType != 3">
                      <div class="price_list" v-show="showKeyboard && !item.priceValue">
                        <div class="price_value"  v-for="(item, index1) in priceList" :key="index1" @click="priceChange(item,index)">{{ item }}</div>
                      </div>
                    </div>
                  </div>
                <!-- 油枪信息 -->
                <div class="oilGun_info" @click="goOilGunSelect(index)">
                  <div class="oilGun_info_top" v-if="isShow&&index==0" @click.stop="showOilGunOrUser('user',index)" style="border-bottom: 1px solid #e5e5e5;margin-bottom: 14px;padding-bottom: 14px;">
                    <div class="oilGun_title">加油员</div>
                    <div class="oilGun_placeholder" style="padding-right: .4rem;color: #333;">{{  oilList[index].userText }}</div>
                  </div>
                  <div class="oilGun_info_top">
                    <div class="oilGun_info_left" @click.stop="showOilGunOrUser('oilGun',index)">
                      <p>油枪</p>
                      <div class="oilGun_placeholder" v-if="!(oilList[index]&&oilList[index].oilGunText)" style="padding-right: .4rem;color: #333;">{{ oilList[index].gunName + ' ' + oilList[index].oilGunText }}</div>
                      <div class="oilGun_value" v-else>
                        <span class="num">{{oilList[index].gunName}}</span>
                        <span class="line">&frasl;</span>
                        <span class="name">{{oilList[index].oilGunText}}</span>
                      </div>
                    </div>
                    <div class="oilGun_info_right" v-if="(index+1 ==oilList.length)&&isAdd" @click="onAddOil(index)"><p class="addOil">+添加油品</p></div>
                  </div>
                  <div class="price" v-show="showRemitPage && !!item.oilOfficialPrice"> 单价：<span class="price_color">￥{{ item.oilOfficialPrice }}/L</span ></div>
                  <div class="manjian" v-show="(CouponDataList[index]&&CouponDataList[index].isShow == 1)&&(CouponDataList[index]&&CouponDataList[index].preferenceMessageList&&CouponDataList[index].preferenceMessageList.length)">
                    <span>限时满减</span>
                    <div>
                      <p v-for="(subitem, index2) in CouponDataList[index]&&CouponDataList[index].preferenceMessageList" :key="index2">
                        <!-- 满0.01元（升） 95#汽油-每升立减40元（%） -->
                        满{{ subitem.full}}{{ subitem.activityType === "AAL" ? "元" : ""}}{{ subitem.activityType === "AALL" ? "升" : "" }}
                        <span>{{oilList[index].oilGunText}}-每升立减{{ subitem.cut}}{{ subitem.activityMode === "FAD" ? "元" : ""}}{{ subitem.activityMode === "PAR" ? "%" : "" }}</span>
                      </p>
                    </div>
                  </div>
                </div>
                <div class="divider_line" :class="[oilGunStatus ? 'active' : '']"></div>
                <template #right>
                  <van-button @click="onRemove(index)" square text="删除" type="danger" class="delete-button" />
                </template>
              </van-swipe-cell>
              <van-number-keyboard  :class="[Number(priceValue) >= 0.01 ? '' : 'disabold']" v-model="oilList[index].priceValue" :maxlength="9" :show="showKeyboard && currentIndex == index" @input="blurInput(index)" theme="custom" close-button-text="确认" extra-key="." @close="onCloseKeyboard(index)"/>
            </div>

            <!-- 支付方式 -->
            <div class="remit_page_container" v-show="showRemitPage && !showCouponList">
              <div class="remit_page_wraper">
                <hr v-if="CouponData.genericEnable === 1" style="height:0.5px; border:none;background:#eee;margin: 0.2rem 0rem;"/>
                <div class="stored_radio">
                  <div class="stored_card">
                    <div class="icon vx"></div>
                    <div class="stored_title">微信</div>
                  </div>
                  <van-radio-group v-model="radioParams">
                    <van-radio name="2" value="2"  v-model="radioParams" checked-color="#FD6B00"></van-radio>
                  </van-radio-group>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 底部支付 -->
      <div class="bottom_fix_bar" v-show="showRemitPage && !showCouponList">
        <div class="fix_bar_main">
          <div class="car_container">
            <div class="newPrice">
              <div class="price_bar">
                总计：
                <span class="price_value">￥{{ this.CouponData.amt }}元</span>
                <span v-show="CouponData.discountAmt > 0 && showRemitPage" style=" color: #ccc; font-size: 0.2rem; text-decoration: line-through; ">¥{{ this.CouponData.finalAmount }}</span>
              </div>
              <div class="price_coupon" v-show="CouponData.isShowPaymentCommission === 1">服务费<span> ￥{{ this.CouponData.channelFeePayer }} 元</span></div>
            </div>
          </div>
          <van-button v-throttle="500" @click="submitRemit()" :loading="btnLoading" :disabled=" (radioParams === '1' && CouponData.amt > CouponData.balance) || (radioParams === '3' && CouponData.amt > CouponData.genericBalance)" type="warning"  loading-text="支付中..." round >立即支付</van-button>
        </div>
      </div>

      <!-- 选择员工油枪弹窗 -->
      <van-popup v-model="oilGunOrUserShow" round position="bottom" :close-on-click-overlay="false" :style="{ height: '60%' }" >
        <div style="height: 100%;display: flex;justify-content: center;align-items: center;">
          <div style="height: 100%;" v-show="swipeIndex === 0">
            <div class="oil-title">
              <span>选择员工</span>
            </div>
            <div class="oil-box">
              <template v-if="userList.length > 0">
                <div class="oil-items" v-for="item in userList" :key="item.userId" @click="changeUserId(item)">
                  <span>{{ item.nickName }}</span>
                </div>
              </template>
              <div v-else style="position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);font-size: 24px;color: #ccc;">
                该油站下暂无员工
              </div>
            </div>
          </div>
          <div style="height: 100%;position: relative;" v-show="swipeIndex === 1">
            <van-icon v-show="(!isHasUserId && isNeedStaff)&&!isStaff" @click="clickBack" name="revoke" size="20" style="position: absolute;top: 25px;left: 10px;"/>
            <div class="oil-title">
              <span>选择油枪</span>
            </div>
            <div class="oil-box">
              <template v-if="oilGunList2.length > 0">
                <div class="oil-items" v-for="item in oilGunList2" :key="item.id" @click="changeOilGunId(item)">
                  <div class="gunName">{{ item.gunName }}</div>
                  <span class="line">&frasl;</span>
                  <div class="oilName">{{ item.oil.oilName + item.oil.oilClass }}</div>
                </div>
              </template>
              <div v-else style="position: absolute;top: 50%;left: 30%;transform: translate(-20%,-50%);font-size: 24px;color: #ccc;" >该员工未绑定油枪</div>
            </div>
          </div>
        </div>
      </van-popup>
    </div>
    <div v-else class="loadingName">
      <p>正在加载中,请耐心等待</p>
    </div>
    <van-overlay :show="updateOrderByCouponLoading">
      <van-loading size="40px" style="text-align:center;top: 50%;"  vertical>加载中...</van-loading>
    </van-overlay>

    <!-- 储值卡支付，需要密码时的密码框 -->
    <van-popup v-model="isShowPasswdKeyboard" position="bottom" :style="{ height: '75%' }">
      <h3 style="text-align:center">输入支付密码</h3>
      <!-- 密码输入框 -->
      <van-password-input :value="password" :focused="isShowPasswdKeyboard" @focus="isShowPasswdKeyboard = true"/>
      <!-- 数字键盘 -->
      <van-number-keyboard v-model="password" theme="custom" close-button-text="完成" :show="isShowPasswdKeyboard" @blur="isShowPasswdKeyboard = false" @close="checkPassword"/>
    </van-popup>

    <!-- 电子卡同一个油站，同一个手机在一分钟内支付订单的提示 -->
    <van-dialog v-model="isRepeatPayshow" message="你已在当前商户支付过一笔相同金额的订单，请确认是否继续支付" cancel-button-text="取消支付" confirm-button-text="继续支付" show-cancel-button @confirm="continuePay"></van-dialog>

    <!-- 油机订单选择： 选择油枪后，去查询油机订单，如果仅30分钟内有，则展示 -->
    <van-popup v-model="isShowOilEnginDialog" :close-on-click-overlay="false" position="bottom" :style="{ height: '70%' }">
      <!-- 空状态 -->
      <div class="order_engin_list" v-if="oilEnginOrderList.length === 0">
        <h3>选择订单</h3>
        <div class="empty">
          <p class="header">
            <b>{{ this.oilGunNum }}号枪</b>
            近10分钟有0笔待支付订单
          </p>
          <div class="bottom" v-if="isInput">
            <span>没有您的订单？可尝试手工输入</span>
            <van-button color="orangered" round size="normal" style="width: 2rem;font-size: 0.3rem;height: 0.8rem;" @click="handleManualInput" >手动输入</van-button >
          </div>
        </div>
      </div>
      <!-- 存在订单 -->
      <div class="order_engin_list" v-if="oilEnginOrderList.length > 0">
        <h3>选择订单</h3>
        <div class="order_engin_item" v-for="(item, index) in oilEnginOrderList" :key="item.id" @click="selectOilEnginItem(item)">
          <p class="p1">
            <span class="gunNumber"> {{ item.oilGun }}</span>
            <span class="gunName">{{ item.oilName }}</span>
          </p>
          <p class="p2">
            <span class="price">
              <b>{{ item.totalPrice }}</b> 元
            </span>
            <span class="time">{{ item.createTime }}</span>
          </p>
        </div>
      </div>
    </van-popup>
  </van-pull-refresh>
</template>

<script>
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
import { getAuthen } from "@/utils/getAuthen";
import wx from "weixin-js-sdk";
import Qr from "@/components/QrCode";
import Vue from "vue";
import throttle from "@/utils/directive";
import qs from "qs"; // 用于解析url获取参数的第三方库
import {
  NumberKeyboard,
  Field,
  Icon,
  Popup,
  Toast,
  Button,
  CouponCell,
  Radio,
  RadioGroup,
  Swipe,
  SwipeItem,
  PullRefresh,
  Loading,
  Overlay,
  Dialog,
  PasswordInput,
  SwipeCell
} from "vant";
Vue.use(NumberKeyboard);
Vue.use(Field);
Vue.use(Icon);
Vue.use(Popup);
Vue.use(Toast);
Vue.use(Button);
Vue.use(CouponCell);
Vue.use(Radio);
Vue.use(RadioGroup);
Vue.use(Swipe);
Vue.use(SwipeItem);
Vue.use(PullRefresh);
Vue.use(Loading);
Vue.use(Overlay);
Vue.use(Dialog);
Vue.use(PasswordInput);
Vue.use(SwipeCell);

export default {
  head() {
    return {
      title: "一键加油"
    };
  },
  data() {
    return {
      radioParams: "2", // 1 储值卡  2 微信支付  3 通用卡支付
      radioCouponsValue: "-1", // 优惠券按钮绑定的值（当前保存是索引值）
      showKeyboard: false, // 键盘显示
      showBottom: false, // 购物车
      showRemitPage: false, // 支付界面
      showCouponList: false, // 优惠劵
      staOilGunList: [],
      oilGunNum: "", // 油枪号
      oilGunName: "", // 油枪名字结合
      oilName: "", // 油枪名字
      oilClass: "", // 油枪类型
      oilId: "", // 油ID
      oilGunStatus: true, // 油枪状态
      priceValue: "", // 价格
      // oilOfficialPrice: "", // 单价
      priceList: ['100', '200', '300', '400'],
      CouponData: {}, // 优惠劵信息
      chosenCoupon: -1, // 优惠劵索引
      couponPrice: "", // 优惠金额
      verticalPrice: "", // 立减
      couponUserId: "", // 优惠卷id
      axiosNum: 0,
      oilGunText: "请选择油枪号",
      userText: "请选择加油员",
      oilGunOrUserShow: false,
      userList: [],
      oilGunList: [],
      oilGunList2: [],
      swipeIndex: 0,
      isHasUserId: false,
      isNeedStaff: true,
      utmSource: 9, // 订单来源 1 扫员工码
      isLoading: false,
      updateOrderByCouponLoading: false, // 修改订单loading
      nonsecretInfo: {}, // 免密支付信息
      passwordShowKeyboard: false, // 密码弹框
      password: "",
      isShowPasswdKeyboard: false, // 控制是否显示密码输入框
      isRepeatPayshow: false, // 控制电子卡重复支付弹框
      isShowOilEnginDialog: false, // 控制是否展示油机订单弹框
      oilEnginOrderList: [], // 油机订单列表
      isTube: false, // 是否开始零托管
      isInput: false, //是否手动控制输入金额
      currentOilEngineInfo: {}, // 当前选择的油机订单信息
      oilList:[{priceValue:'',oilGunNum:'',gunName:'',oilGunText:'请选择油枪号',userText:'请选择加油员',oilOfficialPrice:''}],
      currentIndex:0,
      oliIndex:"",//选择油枪的index
      isAdd:false,//是否展示新增按钮
      ordNoList:[],//订单号列表
      isCreatOn:false,//是否创建订单
      amtList:[],//创建订单的支付金额
      CouponDataList:[],//创建订单相应的数据存储列表
      isStaff:false,//添加油品员工是否弹出
      itemInfo:'',
      btnLoading:false,
      routeShow:false,
      isShowPage:true
    };
  },
  components: {
    Qr: Qr
  },
  // watch: {
  //   coupons: {
  //     handler(list) {
  //       console.log(list, "监听--优惠券列表");
  //     },
  //     immediate: true
  //   }
  // },
  computed: {
    // 优惠券列表数组
    // coupons() {
    //   console.log("计算优惠券数据---coupons", this.CouponData);
    //   const { couponList = [] } = this.CouponData;
    //   return couponList.map(item => {
    //     // couponType：1 现金券  2 折扣券
    //     // couponAmt 优惠金额
    //     // newAmtByCoupon: 优惠后的金额
    //     // issueName:发放方式名称
    //     // 如果 couponType 为2（折扣卷）时 ，couponAmt 为折扣百分比
    //     // couponThresholdAmt  最低消费金额
    //     const couponAmt =
    //       item.couponType === "1"
    //         ? `${item.couponAmt} ￥`
    //         : `${item.couponAmt} %`;
    //     // const value =
    //     //   item.couponType === "1"
    //     //     ? `${item.couponAmt * 100}`
    //     //     : `${(Number(this.priceValue) / item.couponAmt) * 100}`;
    //     const value = Number(this.CouponData.discountCouponAmt) * 100;
    //     return {
    //       ...item,
    //       id: item.couponId,
    //       condition: `满${item.couponThresholdAmt}元可用`,
    //       name: item.couponType === "1" ? "立减劵" : "折扣劵", // 优惠券名称
    //       time: item.couponEffectiveTime,
    //       valueDesc: couponAmt, // 折扣券优惠金额文案
    //       couponUserId: item.couponUserId,
    //       value: Number(value) //  折扣券优惠金额，单位分
    //     };
    //   });
    // },
    newPrice() {
      if(this.oilList.length){
        const totalPrice = this.oilList.reduce((sum, item) => sum + Number(item.priceValue), 0);
        this.priceValue=totalPrice
      }
      if (!!this.couponPrice) {
        return (
          Number(this.priceValue) -this.couponPrice -this.verticalPrice).toFixed(2);
      }
      return Number(this.priceValue - this.verticalPrice).toFixed(2);
    },
    // 优惠总价格
    NewCouponPrice() {
      if (!!this.couponPrice) {
        return (Number(this.couponPrice) + this.verticalPrice).toFixed(2);
      }
      return (this.verticalPrice || 0).toFixed(2);
    },
    isShow() {
      if (this.isHasUserId) {
        return true;
      } else {
        return this.isNeedStaff;
      }
    },
    ...mapGetters({
      userInfo: "authen/userInfo"
    })
  },
  async created() {
    console.log("进入remit页面-userInfo：", this.userInfo);
    console.log("store中的存储的用户信息", this.$store.state.authen.userInfo);
    if (!this.userInfo.mobilePhone) {
      console.log("000--扫码进入--授权");
      getAuthen("", "remit");
      return false;
    }

    let currentUrl = window.location.href;
    // let urlObj = this.getUrlParams(currentUrl);
    // this.getUrlData(currentUrl); //  测试使用原生js的方法获取
    // let urlObj = this.getUrlParamsByQs(currentUrl);
    let urlObj;
    try {
      urlObj = this.getUrlParams(currentUrl);
      if (urlObj === null || urlObj === {}) {
        urlObj = this.getUrlParamsByQs(currentUrl);
      }
    } catch (error) {
      urlObj = this.getUrlParamsByQs(currentUrl);
    }

    console.log("解析url:", urlObj);

    if (urlObj.utmSource) this.utmSource = urlObj.utmSource;
    this.stationId = urlObj.stationId;
    this.userId = urlObj.userId;
    if(urlObj.userId){
      this.routeShow=true
    }
    this.stationName = urlObj.stationName;
    this.appType = urlObj.appType; // 来源类型3:pos机
     console.log('urlObj.itemInfo',urlObj.itemInfo);
    if(urlObj.itemInfo){
      this.itemInfo=JSON.parse(urlObj.itemInfo)
      this.oliIndex=0
      this.oilList[0].userText=urlObj.userName
      this.changeOilGunId(this.itemInfo)
    }
    if (this.appType == 3) {
      this.userText = urlObj.userName; // pos员工名
      this.oilGunName = urlObj.oilName; // 油枪名
      this.oilGunNum = urlObj.gunName; // pos油枪
      this.priceValue = urlObj.price / 100; // 初始金额
      this.showKeyboard = false;
      this.showRemitPage = true;
      this.showCouponList = false;

      this.orderRandomId = urlObj.orderRandomId;
      this.oilGunOrUserShow = false;
      this.isHasUserId = true;
      await this.getPayPosInfo();
      this.radioParams = "2";
    } else {
      this.getOilGunUserList(this.userId);
    }
    this.inspectRegisteredUser();
  },
  methods: {
    onRemove(index){
      if (index >= 0 && index < this.oilList.length) {
        // 使用 splice 删除指定索引的元素
        const removePrice=this.amtList[index]&&this.amtList[index].amt
        const channelFeePayer=this.amtList[index]&&this.amtList[index].channelFeePayer
        this.CouponData.amt= parseFloat(Number(this.CouponData.amt)-Number(removePrice)).toFixed(2)
        console.log('删除金额~~~~this.CouponData.channelFeePayer',this.CouponData.channelFeePayer);
        console.log('删除金额~~~~channelFeePayer',channelFeePayer);
        if(channelFeePayer){
          this.CouponData.channelFeePayer=parseFloat((Number(this.CouponData.channelFeePayer)-Number(channelFeePayer))).toFixed(2)
        }
        this.oilList.splice(index, 1);
        this.ordNoList.splice(index, 1);
        this.amtList.splice(index,1)
        this.CouponDataList.splice(index,1)
      }
      if(this.oilList.length==1){
        this.isAdd=true
        this.isCreatOn=true
      }
    },
    blurInput(index) {
      this.$refs['fieldRef' + index][0].blur();
        this.$nextTick(() => {
          let inputValue = this.oilList[index].priceValue;
          const decimalCount = this.countDecimals(inputValue);
          if (decimalCount > 2) {
            inputValue = String(Number(inputValue).toFixed(2));
            // 提示用户输入最多两位小数
            this.$toast.fail('最多只能输入两位小数');
            // 你可以选择将输入值截断或采取其他处理方式
            // inputValue = inputValue.slice(0, -1);
          }
           this.oilList[index].priceValue = inputValue;
        });
    },
    countDecimals(value) {
      const match = String(value).match(/\.(\d+)$/);
      return match ? match[1].length : 0;
    },
    // 初始化进入判断是否注册成功发券
    inspectRegisteredUser() {
      this.$axios
        .$get("/inspectRegisteredUser", {
          params: { enterpriseId: this.enterpriseId, mobilePhone: this.phone }
        })
        .then(async res => {
          // 如果完全新用户时：基础值是1 ， 领完后再次进入页面, 新用户是最终停留在2。 根据后端接口查看，只调用了一次
          console.log("进入页面的次数", res.data.numberOfEntry);
          if (res.retCode === 0 && res.data.numberOfEntry === 2) {
            // 获取当前用户下所有的优惠券
            const couponRes = await this.$axios.$get("/getRegisterCoupon", {
              params: {
                enterpriseId: this.enterpriseId,
                mobilePhone: this.phone
              }
            });
            console.log("couponRes----", couponRes);
            if (couponRes.data && couponRes.data.length >= 1) {
              Dialog.confirm({
                title: "恭喜获得优惠券！",
                message: "优惠券已到账，马上去查看",
                confirmButtonText: "去查看",
                confirmButtonColor: "gray",
                cancelButtonText: "继续支付",
                cancelButtonColor: "red"
              }).then(() => {
                this.$router.push({
                  path: `/${this.enterpriseId}/coupon`
                });
              });
            }
          }
        });
    },
    // 添加油品
    async onAddOil(index){
      if(!this.oilList[index].priceValue){
        this.$toast.fail('请输入金额')
        return
      }
      if(index==0){
        this.isAdd=false
        const newItem={priceValue:'',oilGunNum:'',gunName:'',oilGunText:'请选择油枪号',oilOfficialPrice:''}
        this.oilList.push(newItem);
        if(this.isShow){
          this.showOilGunOrUser('user',index+1)
          console.log('步骤二',this.oilGunList);
          if(this.oilList.length==2){

          }
          this.oilGunList2= this.oilGunList.filter(item=>{
          return (item.oil && item.oil.oilClass== '柴油')&&item.gunName != this.oilList[index].gunName;})
        }else{
          this.showOilGunOrUser('oilGun',index+1)
          console.log('步骤三',this.oilGunList);
          this.oilGunList2= this.oilGunList.filter(item=>{
            return (item.oil && item.oil.oilClass== '柴油')&&item.gunName != this.oilList[index].gunName;
          })
        }
         console.log('oilGunList2',this.oilGunList2);
      }
      if(index==1){
        this.$toast.fail('最多只能添加两种柴油')
      }
      if(!this.isCreatOn){
        this.getPayInfo(index)
      }
      if(this.oilGunList2.length==0){
          this.oilGunOrUserShow=false
          this.oilList.splice(1, 1);
          this.$toast.fail('当前只有一种柴油，无法进行添加')
          setTimeout(() => {
            this.showKeyboard = true;
            this.$refs.fieldRef0[0].focus()
          }, 500);

          return
        }
    },

    getUrlParamsByQs(url) {
      let urlStr = url.split("?")[1];
      let urlObj = qs.parse(urlStr);
      return urlObj;
    },
    getUrlParams(url) {
      // Object.fromEntries:静态方法将键值对列表转换为一个对象
      // urlSearchParams.entries()方法: 返回一个迭代器，允许遍历该对象中包含的所有键/值对
      let urlStr = url.split("?")[1];
      const urlSearchParams = new URLSearchParams(urlStr);
      const result = Object.fromEntries(urlSearchParams.entries());
      console.log("URLSearchParams---", result);

      return result;
    },

    // 方法2： 使用原生js解析url
    getUrlData(url) {
      //  demo : https://yftx-map-test.xailife.com/174/fuel/remit/?stationId=234&stationName=广东壳牌中山服务区加油站&userId=589&utmSource=1
      // decodeURI : 以UTF-8编码编码字符串，对这些字符：“ ; , / ? : @ & = + $ ”不做编码。
      console.log("原始url：", url);
      console.log("解码后的urldecodeURIComponent", decodeURIComponent(url));

      let fullUrl = decodeURIComponent(url); // 解码
      let urlStr = fullUrl.split("?")[1]; // 获取链接 ？ 后的参数
      let urlParamArr = urlStr.split("&"); // 分割键值对   如果url的参数中存在了 &  会切割不准确的
      let urlObj = {};
      urlParamArr.forEach(item => {
        let key = item.slice(0, item.indexOf("="));
        let val = item.slice(item.indexOf("=") + 1);
        urlObj[key] = val;
        // let itemObj = item.split("=");
        // urlObj[itemObj[0]] = itemObj[1]; // 拼接对象
      });
      return urlObj;
    },

    // 点击油枪
    showOilGunOrUser(key,index) {
      console.log('其味无穷额外企鹅企鹅轻微青蛙',key);
      console.log('创建订单~~~~~CouponDataList',this.CouponDataList);
      // this.CouponDataList.splice(index,1)
      this.currentOilEngineInfo = {}; // 每次点击油枪后， 清空一下油机订单的信息
      if(!(this.userId&&index==0)){
        this.oilList[index].priceValue = ""; // 清空输入框金额
      }


      console.log('油品列表',this.oilList);
      this.amtList.splice(index,1)

      if (this.appType != 3) {
        if (key === "user") {
          console.log('user',index);
          console.log('userId',this.userId);
          if(this.routeShow){
            if(this.userId&&index==0){
              return
            }
          }
          if(this.itemInfo){
              this.oilGunOrUserShow=true
              const routUserId= sessionStorage.getItem('routUserId')
              this.userList.filter(item=>{
                if(item.userId==(this.userId||routUserId)){
                  this.oilGunList=item.gunList
                  this.oilGunList2=item.gunList
                }
              })
          }
          //   else if (this.isHasUserId) {
          //   this.oilGunStatus = false;
          //   this.showRemitPage = false;
          //   this.$toast("通过员工码扫码进入");
          //   return;
          // }
          if(this.oilList.length==2){
            this.isStaff=true
          }else{
            this.isStaff=false
          }
          if(index==0){
            this.amtList=[]
            this.CouponDataList=[]
            this.ordNoList=[]
            this.oilList=[]
            const newItem={priceValue:'',oilGunNum:'',gunName:'',oilGunText:'请选择油枪号',oilOfficialPrice:''}
            this.oilList.push(newItem);
            this.oliIndex=index
            this.swipeIndex =0;
            this.oilGunOrUserShow = true;
            return
          }
          this.swipeIndex =1;
          this.oilGunOrUserShow = true;
          this.oliIndex=index
          this.oilList[index].userText=this.oilList[0].userText
        } else if (key === "oilGun") {
          if(this.oilClass=='柴油'){
            if(index==0){
              this.oilGunList2=this.oilGunList
               const filteredOilGunList2 = this.oilGunList2.filter(gunItem => {
                return !this.oilList.some(oilListItem => {
                  return oilListItem.gunName === gunItem.gunName && oilListItem.gunName !== this.oilList[index].gunName;
                });
              });
             this.oilGunList2=filteredOilGunList2
            }else{
              this.oilGunList2= this.oilGunList.filter(item=>{
              return item.oil && item.oil.oilClass== '柴油';
           })
            const filteredOilGunList2 = this.oilGunList2.filter(gunItem => {
              return !this.oilList.some(oilListItem => {
                return oilListItem.gunName === gunItem.gunName && oilListItem.gunName !== this.oilList[index].gunName;
              });
            });
            this.oilGunList2=filteredOilGunList2
            // 现在 filteredOilGunList2 包含了不在 this.oilList 中的元素
            console.log('filteredOilGunList2',filteredOilGunList2);
            }
          }else{
            console.log('步骤二');

             this.oilGunList2= this.oilGunList.filter(item=>{
              return item.oil && item.oil.oilClass!= '柴油';
           })
           console.log('其他油',this.oilGunList2);
          }
          if(this.itemInfo){
            const routUserId= sessionStorage.getItem('routUserId')
            console.log('1111111111111111~~~~~~~~~oilGun',this.oilList);
            this.userList.filter(item=>{
              if(item.userId==(this.userId||routUserId)){
                this.oilGunList=item.gunList
                this.oilGunList2=item.gunList
              }
            })
            if(index==1){
              this.oilGunList2= this.oilGunList.filter(item=>{
              return item.oil && item.oil.oilClass== '柴油';
           })
            const filteredOilGunList2 = this.oilGunList2.filter(gunItem => {
              return !this.oilList.some(oilListItem => {
                return oilListItem.gunName === gunItem.gunName && oilListItem.gunName !== this.oilList[index].gunName;
              });
            });
            this.oilGunList2=filteredOilGunList2
            // 现在 filteredOilGunList2 包含了不在 this.oilList 中的元素
            console.log('filteredOilGunList2',filteredOilGunList2);
            }
            console.log('222222222222222222222222222~~~~~~~~oilGun`',this.oilGunList);
          }
          this.swipeIndex = 1;
          this.oilGunOrUserShow = true;
          this.oliIndex=index
          this.ordNoList.splice(index, 1);
          this.CouponDataList.splice(index, 1);
        }
      }
    },
    // 获取油枪用户列表
    getOilGunUserList(userId) {
      let data = {
        stationId: this.stationId
      };
      if (userId) data.userId = userId;
      this.$axios
        .$get("/staff/list", {
          params: data
        })
        .then(res => {
          if (res.retCode === 0 && res.data) {
            this.isHasUserId = res.data.hasUserId;
            this.isNeedStaff = res.data.needStaff;
            this.oliIndex=0
            if(this.itemInfo){
              this.oilGunOrUserShow = false
            }else{
              this.oilGunOrUserShow = true;
            }
            this.isTube = res.data.isTube === "0" ? false : true; // 是否开启零托管  0关闭 1 开启
            this.isInput =  res.data.isInput == "1" ? true : false; // 是否手动控制输入金额  0关闭 1 开启
            console.log("开启的关联领管：", this.isTube);
            // 扫码进来
            if (this.isHasUserId) {
              this.userText = res.data.staff.nickName;
              this.oilList[this.oliIndex].userText=res.data.staff.nickName;
              this.oilGunList = res.data.staff.gunList;
              this.oilGunList2 = this.oilGunList;
              this.userId = res.data.staff.userId;
              this.userList = [];
              this.swipeIndex = 1;
              // 主页进来
            } else {
              if (this.isNeedStaff) {
                this.swipeIndex = 0;
                this.userList = res.data.staffList;
                this.oilGunList = [];
                this.oilGunList2=[]
              } else {
                this.oilGunList = res.data.gunList;
                this.oilGunList2=this.oilGunList
                this.swipeIndex = 1;
              }
            }
          } else {
            // Toast("请求失败！！！");
            this.$toast("请求员工油枪数据失败！！！");
          }
        });
    },

    // 点击选择员工
    changeUserId(item) {
      this.oilGunList = item.gunList;
      this.oilGunList2=this.oilGunList
      this.userId = item.userId;
      this.userText = item.nickName;
      this.oilList[this.oliIndex].userText=item.nickName||'请选择加油员'
      this.swipeIndex = 1;
      this.oilGunNum = "";
      this.oilGunName = "";
      this.oilGunText = "请选择油枪号";
    },
    // 点击选择油枪
    changeOilGunId(item) {
      let itemInfo=JSON.stringify(item)
      this.oilList[this.oliIndex].oilGunText=item.oil.oilName + item.oil.oilClass;
      this.oilList[this.oliIndex].priceValue=''
      this.oilList[this.oliIndex].gunName=item.gunName
      this.oilGunText = item.oil.oilName + item.oil.oilClass;
      this.oilGunNum = item.gunName;
      this.oilGunName = item.oil.oilName + item.oil.oilClass;
      this.oilName = item.oil.oilName;
      this.oilClass = item.oil.oilClass;
      if(this.oilClass=='柴油'&&this.oilList.length==1){
        this.isAdd=true
      }else{
        this.isAdd=false
      }
      if(this.oilClass!=='柴油'){
        this.$router.replace({
            // path: `/${this.enterpriseId}/fuel/remitDieselOil2?stationId=${this.stationId}&stationName=${this.stationName}&oil=${this.oilClass}&userId=${this.userId}&itemInfo=${itemInfo}&userName=${this.oilList[0].userText}`
            path: `/${this.enterpriseId}/fuel/remitDieselOil2?stationId=${this.stationId}&stationName=${this.stationName}&oil=${this.oilClass}&itemInfo=${itemInfo}&userName=${this.oilList[0].userText}`
        });
        sessionStorage.setItem('routUserId',(this.userId||Number(sessionStorage.getItem('routUserId'))&&Number(sessionStorage.getItem('routUserId')))||null,)
      }
      this.oilId = item.oilId;
      this.oilList[this.oliIndex].oilOfficialPrice = item.oilStationPrice;
      this.oilGunStatus = false;
      // this.$refs.fieldRef.focus(); // 输入框聚焦
      if(this.itemInfo){
        this.$nextTick(()=>{
          if(this.oilList.length==1){
            console.log('fieldRef0',this.$refs);
            this.$refs.fieldRef0[0].focus();
          }else if(this.oilList.length==2){
            console.log('fieldRef1',this.$refs);
            this.$refs.fieldRef1[0].focus();
          }

        })
      }else{
        this.$refs['fieldRef' + this.oliIndex][0].focus();
      }

      this.showRemitPage = false;
      this.oilGunOrUserShow = false;
      if (this.isTube) {
        // 开启了零托管再去查询油机订单
        this.getOilEnginOrderList(); // 查询油机订单
      }
      // 切换支付渠道
      this.changeAutoPayWay();
    },
    // 点击选择员工和油枪中的返回按钮
    clickBack() {
      this.swipeIndex = 0;
    },
    init() {
      // 获取油站信息列表
      this.$axios
        .$get("/selectStaOilGunList", {
          params: {
            stationId: this.stationId,
            userId: this.userId
          }
        })
        .then(res => {
          if (res.retCode != 0) {
            alert(res.message);
            throw new Error(res.message);
            return false;
          }
          this.staOilGunList = res.data.staOilGunList || [];
        });
      // .catch((err) => {
      //   // alert(err);
      //   if (this.axiosNum === 3) {
      //     alert('网络波动请重新扫码进入')
      //     return false
      //   }
      //   if (this.axiosNum < 3) {
      //     this.axiosNum++
      //     this.init()
      //   }
      // });
    },

    // 删除金额
    deletePrice(index) {
      if (this.appType != 3) {
        this.oilList[index].priceValue=''
        this.amtList.splice(index,1)
        this.CouponDataList.splice(index,1)
      }
      if(this.oilList.length==1&& !this.isAdd){
        this.ordNoList.splice(index,1)
        this.CouponDataList.splice(index,1)
      }
    },
    // 点击价格列表
    async priceChange(item,index) {
      if(this.oilList.length==1&&index==0){
        this.isCreatOn=true
      }else{
        this.isCreatOn=false
      }

      this.oilList[index].priceValue = item;
      this.$refs['fieldRef' + index][0].blur()
      this.showKeyboard = false;
      this.showRemitPage = true;
      this.radioParams = "2";

      if(this.oilList.length==2){
         let allPriceValuesTrue=this.oilList.every(item => item.priceValue !== undefined && item.priceValue !== null&& item.priceValue !== ''&& item.priceValue>0)
          console.log('allPriceValuesTrue',allPriceValuesTrue);
        if(!allPriceValuesTrue){
          this.showRemitPage =false
          this.$toast.fail('请输入正确金额')
          return
        }
        this.ordNoList=[]
        this.amtList=[]
        this.CouponDataList=[]
        async function processOilList() {
          for (let index = 0; index < this.oilList.length; index++) {
            await this.getPayInfo(index);
          }
        }

      // 调用函数
      processOilList.call(this);
      }else{
         await this.getPayInfo(index);
      }
    },
    // 调取优惠劵订单
    async updateOrderByCoupon() {
      this.verticalPrice = "";
      const {
        oilGunNum,
        phone,
        openId,
        stationId,
        newPrice,
        oilId,
        couponNo,
        couponUserId
      } = this;
      const { ordNo } = this.CouponData;
      let cardFlag = "2";
      let genericPay = this.radioParams === "3" ? true : false; // 储值卡支付和微信支付是false，  通用卡支付是true
      if (this.radioParams == "1") {
        cardFlag = "2";
      } else if (this.radioParams == "2") {
        cardFlag = "1";
      }
      this.updateOrderByCouponLoading = true;
      await this.$axios
        .$post("/updateOrderByCoupon", {
          aliUserId: "1",
          appType: "1",
          cardFlag,
          gunName: oilGunNum,
          mobilePhone: phone,
          oilId,
          openId: openId,
          couponNo,
          orderNo: ordNo,
          payType: "wx",
          receivableAmt: newPrice,
          stationId,
          version: "1.0",
          couponUserId,
          genericPay
        })
        .then(res => {
          if (res.retCode == 0) {
            this.CouponData = res.data || {};
            this.ordNo = res.data.ordNo;
            this.verticalPrice = res.data.discountAmt || 0;
          } else {
            this.radioParams = "2";
            throw new Error("储值卡无法交易");
          }
        })
        .catch(function(error) {
          // Toast({
          //   message: "确认订单信息失败，请重试"
          // });
          this.$toast("确认订单信息失败，请重试");
          console.log(error);
        });
      this.updateOrderByCouponLoading = false;
    },

    // 回到选择油枪的页面
    goOilGunSelect() {
      if (this.appType != 3) {
        this.oilGunStatus = true;
        this.showKeyboard = false;
        // this.showRemitPage = false;
      }
    },

    // 返回上一页
    goFuelPage() {
      if (!this.userId) {
        this.$router.replace({ path: `/${this.enterpriseId}/fuel` });
        this.$router.go(-1);
      }
    },
    // 小数点的判断
    isDecimal(num) {
      let data = {};
      data.x = String(num).indexOf(".") + 1;
      data.y = String(num).length - data.x;
      return data;
    },
    // 确认金额
    async onCloseKeyboard(index) {
      console.log('CouponDataList',this.CouponDataList);
      console.log('点击第几个金额~~~~~~',index);
      console.log('oilList',this.oilList);
      let allPriceValuesTrue=this.oilList.every(item => item.priceValue !== undefined && item.priceValue !== null&& item.priceValue !== ''&& item.priceValue>0)
      console.log('allPriceValuesTrue',allPriceValuesTrue);
      if(!allPriceValuesTrue){
         this.$toast.fail('请输入正确金额')
        return
      }
      if(this.oilList[index]&&this.oilList[index].priceValue==''){
        this.$toast.fail('请输入正确金额')
        return
      }
      if(this.oilList.length==1&&index==0){
        this.isCreatOn=true
      }else{
        this.isCreatOn=false
      }
      // if(this.CouponDataList.length>1){
      //   this.CouponDataList=[]
      // }
      if(this.oilList.length==2){
        this.ordNoList=[]
        this.amtList=[]
        this.CouponDataList=[]
        async function processOilList() {
          for (let index = 0; index < this.oilList.length; index++) {
            await this.getPayInfo(index);
          }
        }

      // 调用函数
      processOilList.call(this);
      }else{

         await this.getPayInfo(index);
      }

      this.$refs['fieldRef' + index][0].blur()
      this.showKeyboard = false;
      this.showRemitPage = true;
      this.radioParams = "2";
    },
    // 获取订单信息
    async getPayInfo(index) {
      console.log("微信内调起支付---getPayInfo",this.oilList);
      this.verticalPrice = "";
      this.couponPrice = "";
      this.chosenCoupon = -1; // 当前选中优惠券的索引
      const { oilGunNum, phone, openId, stationId,} = this;
      if(this.ordNoList.length==2){
        let allPriceValuesTrue=this.oilList.every(item => item.priceValue !== undefined && item.priceValue !== null&& item.priceValue !== ''&& item.priceValue>0)
          console.log('allPriceValuesTrue',allPriceValuesTrue);
          if(!allPriceValuesTrue){
            this.$toast.fail('请输入正确金额')
            this.showRemitPage=false
            return
          }
      }

      try {
        const res=await this.$axios
        .$post("/createOrder", {
          aliUserId: "1",
          appType: "1",
          cardFlag: "1",
          gunName: this.oilList[index].gunName,
          mobilePhone: phone,
          newCreatefalg: "1",
          openId: openId,
          orderOriginType: "4",
          payType: "wx",
          receivableAmt: this.oilList[index].priceValue,
          stationId,
          version: "1.0",
          userId: (this.userId||Number(sessionStorage.getItem('routUserId'))&&Number(sessionStorage.getItem('routUserId')))||null,
          utmSource: this.utmSource
        })
        if (res.retCode == 0) {
            const CouponData = res.data || {};
            this.amtList.push({amt:res.data.amt,channelFeePayer:res.data.channelFeePayer})
            if(!this.isAdd&&this.oilList.length==1){
              // this.CouponDataList=[{isShow:null,preferenceMessageList:[],discountAmt:null,activityMode:'',activityOilId:null,activityType: "",cut:null,full: null,rulesId:null,}]
              this.amtList=[{amt:null,channelFeePayer:null}]
              this.amtList[index].amt=CouponData&&CouponData.amt
              this.amtList[index].channelFeePayer=CouponData&&CouponData.channelFeePayer

            }
            if(this.isAdd&&this.oilList.length==1){
              // this.CouponDataList=[{isShow:null,preferenceMessageList:[],discountAmt:null,activityMode:'',activityOilId:null,activityType: "",cut:null,full: null,rulesId:null,}]
              this.amtList=[{amt:null,channelFeePayer:null}]
              this.amtList[index].amt=CouponData&&CouponData.amt
              this.amtList[index].channelFeePayer=CouponData&&CouponData.channelFeePayer

            }
            console.log( '价格数组~~~~~~~~~~~~~~~~~~~~~',this.amtList);



            let sum=0
            let sum2=0
            this.amtList.forEach(item=>{
              if(item.amt){
                sum += Number(item.amt)
              }
              if(item.channelFeePayer){
                sum2+=Number(item.channelFeePayer)
              }

            })
            sum=parseFloat(sum.toFixed(2))
            sum2=parseFloat(sum2.toFixed(2))
            console.log( '价格总数~~~~~~~~~~~~~~~~~~~~~',sum);
            console.log( '服务费总数~~~~~~~~~~~~~~~~~~~~~',sum2);
            this.ordNoList.push({ordNo:res.data.ordNo})
            this.CouponDataList.push(CouponData)
            if(!this.isAdd&&this.oilList.length==1){
              this.ordNoList=[]
              const ordNo={ordNo:res.data.ordNo}
              this.ordNoList[index]=ordNo
              this.CouponDataList[index] = CouponData
            }
            if(this.isAdd&&this.oilList.length==1){
              this.ordNoList=[]
              const ordNo={ordNo:res.data.ordNo}
              this.ordNoList[index]=ordNo
              this.CouponDataList[index] =CouponData
            }
            this.CouponData.amt=sum
            this.CouponData.channelFeePayer=sum2
            if (this.CouponDataList && this.CouponDataList.length > 0 && this.CouponDataList[0].isShowPaymentCommission !== undefined && this.CouponDataList[0].isShowPaymentCommission !== null) {
              this.CouponData.isShowPaymentCommission=this.CouponDataList[0].isShowPaymentCommission
            }
            console.log('订单列表',this.ordNoList);
            console.log("创建订单--", this.CouponData);
            console.log("支付金额--", sum);
            if(this.CouponDataList.length==2&&index==0){
              this.CouponDataList.reverse()
            }
            console.log("CouponDataListCouponDataListCouponDataListCouponDataListCouponDataListCouponDataList", this.CouponDataList);

          }else{
            this.$toast.fail(res.message)
          }
      } catch (error) {
        this.$toast("确认订单信息失败，请重试");
        console.log(error);
      }
    },

    // input获取焦点
    async onFocusField(index) {
      console.log('123213123123',index);
      console.log("点击了金额输入框", this.currentOilEngineInfo);
       this.currentIndex = index;
      if (this.appType == 3) {
        return;
      }
      if (!this.oilGunNum || !this.oilGunName) {
        console.log(123);
        // this.$refs.fieldRef.blur();
        this.$refs['fieldRef' + index][0].blur()
        return;
      }

      // 如果选择了油机订单时，不能二次编辑金额
      if (this.currentOilEngineInfo.id) {
        console.log("存在油机订单id");
        // this.$refs.fieldRef.blur(); // 输入框失去焦点
        this.$refs['fieldRef' + index][0].blur()
        return;
      }
      // 不调动手机键盘
      // this.$refs.fieldRef.blur();
      this.$refs['fieldRef' + index][0].blur()
      this.oilGunStatus = false;
      this.showKeyboard = true;
      this.showRemitPage = false;
    },
    // 取消支付播报
    async onCancel() {
      console.log('取消播报',this.oilList);
      let list=[]
      this.oilList.forEach(item=>{
        list.push({gunName:item.gunName,oilPersonId:(this.userId||Number(sessionStorage.getItem('routUserId'))&&Number(sessionStorage.getItem('routUserId')))||null,})
      })
      const res = await this.$axios.$post("/payOrder/cancel/broadcast", {
          enterpriseId: this.enterpriseId,
          stationId: this.stationId,
          gunList:list
        });
      if (res && res.retCode != 0) {
        throw new Error(`${res && res.message}`);
      }
    },
    // 立即支付
    async submitRemit() {
      this.btnLoading=true
      const _this = this;
       this.updateOrderByCouponLoading=true
      const { openId, stationId } = this;
      // let { ordNo } = this.CouponData;

      if (this.radioParams === "2") {
        //微信支付：根据接口返回的数据，在微信内拉起公众号支付，进行付款操作
        let data = {
          aliUserId: "1",
          newCouponFalg: "1",
          openId,
          orderList:this.ordNoList,
          stationId
        };
        console.log('oilist',this.oilList);
        console.log('data',data);
        let payUrl = "/multiplePay/toThirdPay";
        await this.$axios
          .post(payUrl, data)
          .then(function(response) {
            if (response.data.retCode === 0) {
              const data = response.data.data;
              if (data.thirdPayment === "5") {
                _this.isShowPage=false
                window.location.href = data.redirectUrl;
              } else {
                WeixinJSBridge.invoke(
                  "getBrandWCPayRequest",
                  {
                    appId: data.payAppId,
                    timeStamp: data.payTimeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                    nonceStr: data.paynonceStr, // 支付签名随机串，不长于 32
                    package: data.payPackage, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                    signType: data.paySignType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                    paySign: data.paySign // 支付签名
                  },
                  function(res) {
                    if (res.err_msg === "get_brand_wcpay_request:ok") {
                      // 使用以上方式判断前端返回,微信团队郑重提示：
                      //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                      if (_this.couponUserId) {
                        _this.$axios
                          .post("/updateCouponUser", {
                            couponUserId: _this.couponUserId
                          })
                          .then(res => {
                            console.log(res);
                          });
                      }
                      // 更新油机订单状态， 如果选择了油机订单去支付才会更新订单
                      if (_this.currentOilEngineInfo.id) {
                        _this.updateOilEnginOrderStatus();
                      }
                      _this.$toast("支付成功");
                      _this.$router.replace({
                        path: `/${_this.enterpriseId}/fuel/success?ordNo=${ordNo}`
                      });
                    } else {
                      _this.goOilGunSelect();
                      _this.onCancel();
                      _this.$toast("支付失败，请重试");
                    }
                  }
                );
              }
            } else {
              _this.goOilGunSelect();
              _this.$toast("获取支付信息失败，请重试");
            }
          })
          .catch(function(error) {
            _this.goOilGunSelect();
            _this.$toast("获取下单信息失败，请重试");

            console.log(error);
          });
      } else if (_this.radioParams === "1" || _this.radioParams === "3") {
        //  radioParams ： 1 储值卡    3 通用卡
        let genericPay = _this.radioParams === "3" ? true : false;

        // 判断电子卡是否重复支付
        let repeatPayInfo = await _this.$axios.$get("/checkDzkRepeatPay", {
          params: {
            ordNo: ordNo
          }
        });
        if (repeatPayInfo.retCode === -1) {
          _this.isRepeatPayshow = true; // 打开重复支付弹框
        } else {
          _this.isRepeatPayshow = false;

          // 获取免密支付信息
          let info = await _this.$axios.$get("/selectfree", {
            params: {
              enterpriseId: this.enterpriseId,
              mobilePhone: this.phone
            }
          });
          this.nonsecretInfo = info.data;

          // 判断是否开启了免密 （isFree：  0 表示开启免密，1 表示关闭免密 ）.  如果是1显示密码框
          if (info.data.isFree === "1") {
            this.password = "";
            this.isShowPasswdKeyboard = true;
          } else {
            await _this.$axios
              .$get("/newDzkCouponPaySetV3", {
                params: {
                  ordNo,
                  couponUserId: _this.couponUserId,
                  genericPay: genericPay
                }
              })
              .then(res => {
                if (res.retCode != 0) {
                  _this.goOilGunSelect();
                  throw new Error("支付失败!" + res.message);
                } else {
                  _this.$toast("支付成功");
                  // 更新油机订单状态， 如果选择了油机订单去支付才会更新订单
                  if (_this.currentOilEngineInfo.id) {
                    _this.updateOilEnginOrderStatus();
                  }
                  _this.$router.replace({
                    path: `/${_this.enterpriseId}/fuel/success?ordNo=${ordNo}`
                  });
                }
              })
              .catch(err => {
                _this.goOilGunSelect();
                alert(err);
              });
          }
        }
      } else {
        _this.goOilGunSelect();
        return;
      }
      this.btnLoading=false
      this.updateOrderByCouponLoading=false
    },

    //储值卡的密码 确认按钮， 继续支付按钮 --- 校验密码
    async checkPassword() {
      let { ordNo } = this.CouponData;
      //  radioParams ： 1 储值卡    3 通用卡
      let genericPay = this.radioParams === "3" ? true : false;

      if (!this.password) {
        this.$dialog
          .alert({
            message: "请输入密码"
          })
          .then(() => {
            this.isShowPasswdKeyboard = true; // 打开密码框
          });
        return;
      }

      // 密码校验
      const res = await this.$axios.$post("/check", {
        ids: this.nonsecretInfo.ids, // 电子卡的id集合
        payPassword: this.password
      });
      if (res.data) {
        await this.$axios
          .$get("/newDzkCouponPaySetV3", {
            params: {
              ordNo: ordNo,
              couponUserId: this.couponUserId,
              genericPay: genericPay
            }
          })
          .then(res => {
            if (res.retCode != 0) {
              this.goOilGunSelect();
              throw new Error("支付失败!" + res.message);
            } else {
              this.$toast("支付成功");
              if (this.currentOilEngineInfo.id) {
                this.updateOilEnginOrderStatus();
              }
              this.$router.replace({
                path: `/${this.enterpriseId}/fuel/success?ordNo=${ordNo}`
              });
            }
          })
          .catch(err => {
            this.goOilGunSelect();
            alert(err);
          });
      } else {
        this.$dialog
          .confirm({
            message: res.message,
            confirmButtonText: "重试"
          })
          .then(res => {
            console.log("确认重试", res);
            this.password = "";
            this.isShowPasswdKeyboard = true;
          })
          .catch(err => {
            console.log("取消输入密码");
            this.isShowPasswdKeyboard = false;
          });
      }
    },

    // 重复支付提示的继续支付
    async continuePay() {
      const _this = this;
      let { ordNo } = this.CouponData;
      let genericPay = _this.radioParams === "3" ? true : false; // true ： 使用通用卡   false:使用储值卡

      // 获取免密支付信息
      let info = await _this.$axios.$get("/selectfree", {
        params: {
          enterpriseId: this.enterpriseId,
          mobilePhone: this.phone
        }
      });
      this.nonsecretInfo = info.data;
      // 判断是否开启了免密  0 表示开启免密，1 表示关闭免密
      if (info.data.isFree === "1") {
        this.password = "";
        this.isShowPasswdKeyboard = true; // 弹出密码框
      } else {
        await _this.$axios
          .$get("/newDzkCouponPaySetV3", {
            params: {
              ordNo,
              couponUserId: _this.couponUserId,
              genericPay: genericPay
            }
          })
          .then(res => {
            if (res.retCode != 0) {
              _this.goOilGunSelect();
              // throw new Error("储值卡支付失败");
              throw new Error("支付失败!" + res.message);
            } else {
              _this.$toast("支付成功");
              // 更新油机订单状态
              if (_this.currentOilEngineInfo.id) {
                _this.updateOilEnginOrderStatus();
              }
              _this.$router.replace({
                path: `/${_this.enterpriseId}/fuel/success?ordNo=${ordNo}`
              });
            }
          })
          .catch(err => {
            _this.goOilGunSelect();
            alert(err);
          });
      }
    },

    // 查询油机订单列表
    async getOilEnginOrderList() {
      const res = await this.$axios.$post("/engine/list", {
        oilGun: this.oilGunNum,
        stationId: this.stationId
      });
      this.oilEnginOrderList = res.data;
      this.isShowOilEnginDialog = true; // 打开油机订单弹框
    },

    // 查询没有油机订单时，点击了手动输入
    handleManualInput() {
      this.isShowOilEnginDialog = false;
      this.currentOilEngineInfo = {}; // 清空当前选择的油机订单信息
      this.priceValue = "";
    },

    // 选择一个油机订单
    selectOilEnginItem(item) {
      console.log(item);
      this.currentOilEngineInfo = item;
      this.priceValue = String(item.totalPrice); // 输入框的金额
      this.isShowOilEnginDialog = false; // 关闭油机订单弹框
      this.showKeyboard = false; // 隐藏输入金额数字键盘
      this.onCloseKeyboard(); // 直接调用确认金额事件，去创建订单
    },

    // 更新油机订单状态
    updateOilEnginOrderStatus() {
      this.$axios.$post("/engine/payment", {
        id: this.currentOilEngineInfo.id
      });
      console.log("更新油机订单状态成功");
    },

    // 自动切换支付渠道
    changeAutoPayWay() {
      this.$axios.$post("/changeAutoPayWay", {
        oilGun: this.oilGunNum,
        stationId: this.stationId
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.remitDiv {
  background-color: rgb(245, 246, 247);
  min-height: 100vh;
  position: relative;
  padding-bottom: 3rem;
  overflow: auto;
}
.loadingName{
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
    p{
      font-size: 18px;
      font-weight: bold;
      color: #666666;
    }
}
.top_bg {
  width: 100vw;
  height: 4rem;
  // background: url("../static/fuel/pay-bg.png") no-repeat;
  background: url("../../../static/fuel/pay-bg.png") no-repeat;
  background-size: 100% 100%;
}

// 油机订单弹框列表css
.order_engin_list {
  width: 100%;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  .empty {
    width: 90%;
    .header {
      font-size: 0.3rem;
    }
    .bottom {
      display: flex;
      align-items: center;
      font-size: 0.3rem;
      justify-content: space-between;
    }
  }
  .order_engin_item {
    width: 6rem;
    height: 1.5rem;
    background: #249bff;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: flex-start;
    border-radius: 0.2rem;
    padding: 0.2rem;
    margin-bottom: 0.2rem;
    .p1 {
      margin: 0;
      .gunNumber {
        font-size: 0.4rem;
        color: #ffe04f;
        font-weight: bold;
      }
      .gunName {
        font-size: 0.25rem;
        color: #ffe04f;
      }
    }
    .p2 {
      margin: 0;
      display: flex;
      justify-content: space-between;
      width: 100%;
      align-items: center;
      color: #fff;
      .price {
        font-size: 0.28rem;
        b {
          font-size: 0.5rem;
          font-weight: bold;
        }
      }
      .time {
        font-size: 0.28rem;
        color: #ffe04f;
      }
    }
  }
}

::v-deep .field_price > div:nth-child(1) {
  width: 1em;
  height: auto;
}

.fuel_remit_wraper {
  box-sizing: border-box;
  // min-height: 100vh;
  width: 90vw;
  margin: auto;
  position: absolute;
  left: 0;
  right: 0;
  top: 0.3rem;

  // &.active {
  //   // background-color: #fff;
  // }

  .fuel_remit_nav {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0.32rem 0.24rem;
    background-color: #fff;
    border-bottom: 2px dashed #f5f5f5;
    border-radius: 0.3rem 0.3rem 0rem 0rem;

    .icon_fixed {
      width: 0.32rem;
      height: 0.32rem;
      // background: url("../static/fuel/fixed.png") no-repeat 0 0;
      background: url("../../../static/fuel/fixed.png") no-repeat 0 0;
      background-size: 100% 100%;
    }

    .name {
      font-size: 0.32rem;
      max-width: 80vw;
      color: #333;
    }

    .icon_right {
      width: 0.32rem;
      height: 0.32rem;
      background: url("../../../static/fuel/right.png") no-repeat 0 0;
      // background: url("../static/fuel/right.png") no-repeat 0 0;
      background-size: 100% 100%;
    }
  }

  .van-number-keyboard {
    &.disabold .van-key--blue {
      background-color: #eaeaea;
    }
  }

  .remit_container {
    .oilGun_container {
      margin-bottom: 250px;
      background-color: rgb(245, 246, 247);
      z-index: 9999;
      .fuel_remit_top {
        padding: 0.24rem;
        box-sizing: border-box;
        width: 100%;
        background-color: #fff;
        border-radius: 0rem 0rem 0.3rem 0.3rem;
        margin-bottom: 10px;
        /deep/.van-button--normal{
          margin-left: 5px;
        }

        &.active {
          padding-bottom: 0.2rem;
          border-radius: 0rem 0rem 0.3rem 0.3rem;
        }

        .oilGun_info {
          min-height: 0.52rem;
          margin-top: 0.3rem;
          border-top: 1px solid #e5e5e5;
          padding-top: 0.3rem;

          .oilGun_info_top {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
            .oilGun_info_left{
              display: flex;
              align-items: center;
              justify-content: space-between;
              flex: 2;
              .oilGun_title {
              font-size: 0.32rem;
              font-weight: 500;
              margin-right: 0.32rem;
              color: #333;
            }

            .oilGun_placeholder {
              color: #aeaeae;
              font-size: 0.28rem;
              font-weight: 500;
            }

            }
            .oilGun_info_right{
              .addOil{
                border-radius: 0.75rem;
                font-size: 13px;
                color: #fff;
                background-color: #249bff;
                margin-left: 10px;
                padding: 2.5px 7.5px;
              }
            }
          }
          .oli_icon_close {
            width: 0.28rem;
            height: 0.28rem;
            background: url("../../../static/fuel/close.png") no-repeat 0 0;
            // background: url("../static/fuel/close.png") no-repeat 0 0;
            background-size: 100% 100%;
            position: absolute;
            right: 0.24rem;
          }

          .oilGun_value {
            padding-right: 0.4rem;
            color: #333;

            .num {
              font-size: 0.4rem;
              font-weight: 600;
            }

            .name {
              font-size: 0.28rem;
            }
          }

          .price {
            color: #999;
            font-size: 0.27rem;
            margin-top: 0.3rem;
          }
          .manjian {
            color: #999;
            border-top: 1px solid #ddd;
            padding-top: 0.2rem;
            margin-top: 0.3rem;
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: flex-start;
            font-size: 0.29rem;
            div {
              width: 75%;
              text-align: right;

              p {
                padding: 0;
                margin: 0rem 0rem 0.1rem 0rem;
                span {
                  color: #32af51;
                }
              }
            }
          }
        }
        .divider_line {
          position: relative;
          width: 100%;
          margin: 0.16rem 0;
          background: #fff;

          // &.active {
          //   // background-color: #98cda7;
          // }


          &.input {
            margin: 0;
            background: #fff;

            .price_list {
              display: flex;
              margin-top: 0.2rem;
              margin-bottom: 0.3rem;
              background: #fff !important;

              .price_value {
                width: 1.64rem;
                text-align: center;
                height: 0.7rem;
                line-height: 0.7rem;
                font-size: 0.26rem;
                background-color: #fff;
                border: 1px solid #f6f6f6;
                margin-right: 0.1rem;
                border-radius: 0.16rem;
                display: flex;
                justify-content: center;
                align-items: center;

                &:nth-child(4n) {
                  margin-right: 0;
                }
              }
            }

            // &.active {
            //   // background-color: #98cda7;
            // }
          }
        }

        .amount_of_money {
          .amount_of_money_title {
            font-size: 0.32rem;
            font-weight: 500;
            margin-bottom: 0.2rem;
            color: #333;
          }

          .field_price {
            height: 1rem;
            background: #f7f9fc;
            border: 1px solid #e5e5e5;
            border-radius: 0.2rem;
            display: flex !important;
            flex-direction: row;
            align-items: center !important;

            &.placeStyle .van-field__body input {
              font-size: 0.4rem;
              font-weight: 600;
            }
          /deep/.van-field__body {
              font-size: 0.4rem;
              font-weight: 600;
            }
            .icon_close {
              width: 0.28rem;
              height: 0.28rem;
              background: url("../../../static/fuel/close.png") no-repeat 0 0;
              // background: url("/../static/fuel/close.png") no-repeat 0 0;
              background-size: 100% 100%;
            }

            .van-field__body {
              input {
                font-size: 0.4rem;
                font-weight: 600;
              }
            }

            .discountAmt {
              font-size: 0.28rem;
              color: #32af51;
            }

            .van-field__label {
              color: #333;
              font-size: 0.32rem;
              font-weight: 500;
              width: auto;
              margin-right: 0.32rem;
            }
          }

          // .van-cell {
          //   padding: 6px 16px;
          // }
        }
      }

      .oilGun_main_wraper {
        display: flex;
        flex-direction: column;
        align-items: center;
        // padding: 0 0.24rem;
        margin-top: 0.52rem;

        .oilGun_main_title {
          height: 1.1rem;
          line-height: 1.1rem;
          font-size: 0.28rem;
          font-weight: 600;
        }

        .oilGun_main_content {
          width: 100%;
          display: flex;
          flex-wrap: wrap;

          .main_card {
            position: relative;
            width: 1.9rem;
            height: 0.8rem;
            margin: 0rem 0.2rem 0.2rem 0rem;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;
            background: #f7f9fc;
            border: 1px solid #e5e5e5;
            border-radius: 0.16rem;
            overflow: hidden;

            &.active {
              // background-color: #34b053;
              border: 1px solid #fd6b00;
              opacity: 0.8;
              color: #fd6b00;

              .gunName {
                color: #fd6b00;
              }

              .oilName {
                color: #fd6b00;
              }

              .active_icon {
                display: inline-block !important;
              }
            }

            &:nth-child(3n) {
              margin: 0 0 0.08rem 0;
            }

            .line {
              margin-right: 0.04rem;
              margin-left: 0.06rem;
            }

            .gunName {
              font-size: 0.36rem;
              font-weight: 600;
              color: #333;
              margin-bottom: 0.1rem;
            }

            .oilName {
              font-size: 0.24rem;
              // color: #fd6b00;
            }

            .active_icon {
              width: 14px;
              height: 10px;
              position: absolute;
              right: 0;
              bottom: 0;

              img {
                width: 100%;
              }
            }
          }
        }
      }

      .remit_page_container {
        background-color: #fff;
        padding: 0.3rem;
        margin-top: 0.4rem;
        border-radius: 0.3rem;

        .remit_page_wraper {
          // padding: 0.32rem 0.28rem 0.4rem;
          // background-color: #f6f6f6;
          // border-radius: 0.2rem;

          .stored_radio {
            height: 1rem;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .stored_card {
              display: flex;
              align-items: center;
              font-size: 0.32rem;
              font-weight: 600;
              color: #333;
              margin-left: 0.16rem;

              .icon {
                width: 0.6rem;
                height: 0.6rem;
                margin-right: 0.16rem;
                border: 1px dashed #ddd;

                &.stored {
                  // background: url("../../../static/vip/a1.svg") no-repeat 0 0;
                  background: url("../../../static/fuel/pay-cxk.png") no-repeat
                    0 0;
                  // background: url("../static/fuel/pay-cxk.png") no-repeat 0 0;
                  background-size: 100% 100%;
                }

                &.vx {
                  // background: url("../../../static/fuel/vx_remit.png") no-repeat
                  background: url("../../../static/fuel/pay-wx.png") no-repeat 0
                    0;
                  // background: url("../static/fuel/pay-wx.png") no-repeat 0
                  // 0;
                  background-size: 100% 100%;
                }
              }
            }
          }

          .stored_amt {
            font-size: 0.24rem;
            color: #9095ad;
            padding: 0.1rem 0rem;
          }

          .divider_line {
            width: 100%;
            height: 1px;
            margin: 0.16rem 0;
            background-color: #eee;
          }
        }
      }

      .coupon_info {
        height: 1.3rem;
        margin-top: 0.3rem;
        background: #fff;
        display: flex;
        align-items: center;
        padding: 0rem 0.3rem 0rem 0.46rem;
        border-radius: 0.3rem;

        .van-cell {
          display: flex;
          flex-direction: row;
          align-items: center;
          background-color: transparent;
          flex: 1;
          padding: 10px 0px;
          font-size: 0.32rem;
          font-weight: 600;
        }

        img {
          width: 0.6rem;
          height: 0.6rem;
          margin-right: 0.16rem;
          border: 1px dashed #ddd;
        }
      }
    }
    /deep/.van-button{
      height: 100%;
    }
  }

  .popup_container {
    .title {
      width: 100%;
      text-align: center;
      height: 1.5rem;
      line-height: 1.5rem;
      font-size: 0.36rem;
      font-weight: 600;
    }

    .popup_main {
      .popup_name {
        box-sizing: border-box;
        padding: 0 0.2rem;
        width: 100%;
        background-color: #f5f6f7;
        height: 0.8rem;
        line-height: 0.8rem;
      }

      .popup_price {
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        height: 0.8rem;
        padding: 0 0.2rem;

        .tag {
          color: #666;
        }

        .price {
          color: #666;
        }
      }

      // .popup_preferential {
      // }
    }
  }

  .coupons_popup_container {
    .title {
      width: 100%;
      text-align: center;
      height: 1.1rem;
      line-height: 1.1rem;
      font-size: 0.36rem;
      font-weight: 600;
    }

    .van_popup_main {
      .popup_list {
        box-sizing: border-box;
        padding: 0.3rem;
        margin: 0.3rem;
        background-color: #f5f6f7;
        border-radius: 0.16rem;
        display: flex;

        .left_popup {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          width: 2.2rem;
          height: 1.7rem;
          background: url("../../../static/coupon/quan1.2x.png") no-repeat 0 0;
          // background: url("../static/coupon/quan1.2x.png") no-repeat 0 0;
          background-size: 100% 100%;
          color: #fff;
          margin-right: 8px;

          .valueDesc {
            font-size: 0.4rem;
            margin-bottom: 0.32rem;
          }

          .condition {
            font-size: 0.28rem;
          }

          &.red {
            background: url("../../../static/coupon/quan2.2x.png") no-repeat 0 0;
            // background: url("../static/coupon/quan2.2x.png") no-repeat 0 0;
            background-size: 100% 100%;
          }
        }

        .right_popup {
          display: flex;
          flex-direction: column;
          justify-content: space-between;

          .name {
            width: 1.5rem;
            text-align: center;
            height: 0.6rem;
            line-height: 0.6rem;
            background-color: #fad25e;
            border-radius: 0.6rem;

            &.red {
              background-color: #ed9381;
            }
          }

          // .title {
          // }
        }

        .radio {
          position: absolute;
          right: 0.32rem;

          input {
            zoom: 1.5;
          }
        }
      }
    }
  }
}

.bottom_fix_bar {
  // z-index: 9999;
  width: 100%;
  position: fixed;
  background-color: #fff;
  bottom: 0;
  display: flex;
  justify-content: space-between;
  padding: 0.2rem 0rem;

  .fix_bar_main {
    width: 90vw;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: auto;

    .car_container {
      display: flex;
      align-items: center;
      flex: 1;
      // border-top: 1px solid #eee;

      .icon_car {
        width: 0.6rem;
        height: 0.4rem;
        margin-right: 0.3rem;
        margin-left: 0.36rem;

        .van-info {
          background-color: #32af51;
        }
      }

      .price_bar {
        font-size: 0.28rem;
        color: #fc474b;

        .price_value {
          font-size: 0.32rem;
          font-weight: 600;
        }
      }

      .price_coupon {
        font-size: 0.2rem;
        color: #999;
        // font-weight: 500;

        .coupon_value {
          color: #32af51;
        }
      }
    }

    .van-button--warning {
      background-color: #fd6b00;
      height: 0.9rem;
    }

    .van-button--normal {
      padding: 0 23px;
    }
  }
}

.oil-box {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  height: 80%;
  width: 300px;
  justify-content: space-between;
  align-content: baseline;
  overflow-y: scroll;
  margin-top: 10px;

  .oil-items {
    width: 49%;
    height: 0.9rem;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f2f2f2;
    margin-top: 0.2rem;
    border-radius: 5px;

    span {
      font-size: 16px;
    }

    .line {
      margin-right: 0.04rem;
      margin-left: 0.06rem;
    }

    .gunName {
      font-size: 0.4rem;
      font-weight: 600;
      color: #333;
      margin-bottom: 0.1rem;
    }

    .oilName {
      font-size: 0.28rem;
      // color: #fd6b00;
    }
  }

  // .oil-items:last-child {
  //   margin-bottom: 50px;
  // }
}

.oil-box::-webkit-scrollbar {
  display: none;
}

.oil-title {
  width: 300px;
  text-align: center;
  border-bottom: 1px solid #333;
  padding: 20px 0 10px 0;

  span {
    font-size: 19px;
    font-weight: 400;
    display: inline-block;
  }
}
</style>
